//
//  MineMatrixView.swift
//  SCA
//
//  Created by tjun on 2025/9/21.
//

import UIKit

let cellMagin: CGFloat = 12
let matrixleftMarin: CGFloat = 30

class MineMatrixView: UIView, UICollectionViewDataSource, UICollectionViewDelegate {

    var datas: [MineMatrixModel] = [
        MineMatrixModel(text: "0G", hasData: true, isMain: false),
        MineMatrixModel(text: "0G", hasData: true, isMain: false),
        MineMatrixModel(text: "0G", hasData: true, isMain: false),
        MineMatrixModel(text: "0G", hasData: true, isMain: false),
        MineMatrixModel(text: "0G", hasData: true, isMain: false),
        MineMatrixModel(text: "0G", hasData: true, isMain: false),
        MineMatrixModel(text: "0G", hasData: true, isMain: false),
        MineMatrixModel(text: "0G", hasData: true, isMain: false),
        MineMatrixModel(text: "0G", hasData: true, isMain: false),
        MineMatrixModel(text: "0G", hasData: true, isMain: false),
    ]

    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = cellMagin
        layout.minimumInteritemSpacing = 0
        
        let itemSizeW = (screenWidth - matrixleftMarin * 2 - (4 * layout.minimumLineSpacing)) / 5
        layout.itemSize = CGSizeMake(itemSizeW, itemSizeW)
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = AppStyle.color.background
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.alwaysBounceVertical = false
        collectionView.isScrollEnabled = false
        collectionView.register(MineMatrixCell.self, forCellWithReuseIdentifier: MineMatrixCell.identifier)
        return collectionView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
  
        collectionView.addTo(self)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
            
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datas.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model = datas[indexPath.row]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MineMatrixCell.identifier, for: indexPath) as! MineMatrixCell
        cell.model = model
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
                
        
    }
}

class MineMatrixContentView: UIView, UICollectionViewDataSource, UICollectionViewDelegate {
    
    var datas: [MineMatrixModel] = []
    
    private lazy var flowLayout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
   
        layout.minimumLineSpacing = cellMagin
        layout.minimumInteritemSpacing = 0

        let itemSizeW = (screenWidth - matrixleftMarin * 2 - (4 * layout.minimumLineSpacing)) / 5

        layout.itemSize = CGSizeMake(itemSizeW, itemSizeW)
        return layout
    }()
    
    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: self.flowLayout)
        collectionView.backgroundColor = AppStyle.color.background
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.alwaysBounceVertical = true
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(MineMatrixCell.self, forCellWithReuseIdentifier: MineMatrixCell.identifier)
        return collectionView
    }()
    
    private let topArrowButton = UIButton(image: UIImage(named: "matrixUp"))
    private let downArrowButton = UIButton(image: UIImage(named: "matrixDown"))

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        for _ in 1...25 {
            datas.append(MineMatrixModel(text: "-", hasData: true, isMain: true))
        }
        
        topArrowButton.addTo(self)
        topArrowButton.isEnabled = false
        topArrowButton.tintColor = .gray.withAlphaComponent(0.1)
        topArrowButton.addTarget(self, action: #selector(topArrowButtonTapped), for: .touchUpInside)
        topArrowButton.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.centerX.equalToSuperview()
            make.width.height.equalTo(40)
        }

        let itemSizeW = (screenWidth - matrixleftMarin * 2 - (4 * flowLayout.minimumLineSpacing)) / 5

        let leftMatrixViewW = 2 * itemSizeW + flowLayout.minimumLineSpacing
        let leftMatrixViewH = itemSizeW * 5 + 4 * flowLayout.minimumLineSpacing

        let leftMatrixView = MineMatrixView().addTo(self)
        leftMatrixView.snp.makeConstraints { make in
            make.top.equalTo(topArrowButton.snp.bottom)
            make.left.equalTo(matrixleftMarin)
            make.width.equalTo(leftMatrixViewW)
            make.height.equalTo(leftMatrixViewH)
        }
        
        let rightMatrixView = MineMatrixView().addTo(self)
        rightMatrixView.snp.makeConstraints { make in
            make.top.equalTo(leftMatrixView)
            make.right.equalTo(-matrixleftMarin)
            make.width.equalTo(leftMatrixViewW)
            make.height.equalTo(leftMatrixViewH)
        }
     
        collectionView.addTo(self)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(leftMatrixView)
            make.left.equalTo(leftMatrixView.snp.right)
            make.right.equalTo(rightMatrixView.snp.left)
            make.height.equalTo(leftMatrixViewH)
        }
        
        downArrowButton.addTo(self)
        downArrowButton.addTarget(self, action: #selector(downArrowButtonTapped), for: .touchUpInside)
        downArrowButton.snp.makeConstraints { make in
            make.top.equalTo(collectionView.snp.bottom)
            make.centerX.equalToSuperview()
            make.width.height.equalTo(topArrowButton)
            make.bottom.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datas.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model = datas[indexPath.row]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MineMatrixCell.identifier, for: indexPath) as! MineMatrixCell
        cell.model = model
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        
        
    }
    
    private var currentIndex: Int = 0 // 当前滚动到的位置
    
    @objc func topArrowButtonTapped() {
        guard currentIndex > 0 else { return }   // 已经到顶，不滚
        currentIndex -= 1
        collectionView.scrollToItem(at: IndexPath(item: currentIndex, section: 0),
                                    at: .bottom, animated: true)
        updateArrowState()
    }
    
    @objc func downArrowButtonTapped() {
        guard currentIndex < datas.count - 1 else { return }  // 已经到底，不滚
        currentIndex += 1
        collectionView.scrollToItem(at: IndexPath(item: currentIndex, section: 0),
                                    at: .top, animated: true)
        updateArrowState()
    }

    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
          updateArrowState()
      }

      private func updateArrowState() {
          let offsetY = collectionView.contentOffset.y
          let maxOffsetY = collectionView.contentSize.height - collectionView.bounds.height

          // 顶部
          if offsetY <= 0 {
              topArrowButton.isEnabled = false
              topArrowButton.tintColor = .gray.withAlphaComponent(0.1)
          } else {
              topArrowButton.isEnabled = true
              topArrowButton.tintColor = .white
          }

          // 底部
          if offsetY >= maxOffsetY {
              downArrowButton.isEnabled = false
              downArrowButton.tintColor = .gray.withAlphaComponent(0.1)
          } else {
              downArrowButton.isEnabled = true
              downArrowButton.tintColor = .white
          }
      }
}

 

struct MineMatrixModel {
    let text: String
    let hasData: Bool
    let isMain: Bool
    let isHeightLight: Bool = false
}

class MineMatrixCell: BaseCollectionViewCell {

    private let backgroundImageView = UIImageView()
    private let textLabel = GradientTextLabel(font: UIFontMake(14))

    var model: MineMatrixModel! {
        didSet {
            guard let model = model else { return }
            
            backgroundImageView.image = UIImage(named: model.isMain ? "greyGradient" : "referralNetwork_border")
            textLabel.text = model.text
            
            if model.isMain {
                textLabel.colors = [UIColorMake(0xA6A9AF), UIColorMake(0x3E3A39)]
                textLabel.alpha = 1
                backgroundImageView.alpha = 1
            } else {
                if model.isHeightLight {
                    backgroundImageView.alpha = 1
                    textLabel.alpha = 1
                } else {
                    backgroundImageView.alpha = 0.3
                    textLabel.alpha = 0.7
                }
                textLabel.colors = [UIColorMake(0x05D4FC), UIColorMake(0xBE0DEF), UIColorMake(0xF202D3)]
            }
            
      
        }
    }
    
    override func setSubView() {
        super.setSubView()
        
        backgroundImageView.addTo(contentView)
        backgroundImageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        textLabel.addTo(backgroundImageView)
        textLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

}
